package com.alpha.eceasy.mall.config;

import cn.hutool.json.JSONUtil;
import com.alpha.eceasy.auth.BaseUserDetailsService;
import com.alpha.eceasy.auth.LoginUser;
import com.alpha.eceasy.exception.BizException;
import com.alpha.eceasy.exception.ErrorCodeEnum;
import com.alpha.eceasy.mall.api.entity.MallCustomer;
import com.alpha.eceasy.mall.mapper.MallCustomerMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class MallUserDetailsServiceImpl implements BaseUserDetailsService<MallCustomer> {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private MallCustomerMapper mallCustomerMapper;

    @Override
    public LoginUser<MallCustomer> loadUserByUsername(String username) throws UsernameNotFoundException {
        String key = "login_user_info:" + username;
        MallCustomer mallCustomer;
        // 使用userId从redis中查询对应的LoginUser对象
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(key))) {
            String MallCustomerJson = stringRedisTemplate.boundValueOps(key).get();
            mallCustomer = JSONUtil.toBean(MallCustomerJson, MallCustomer.class);
        } else {
            mallCustomer = mallCustomerMapper.selectOne(Wrappers.<MallCustomer>lambdaQuery()
                    .eq(MallCustomer::getUsername, username));
            if (mallCustomer == null) {
                throw new BizException(ErrorCodeEnum.USER_NOT_EXIST);
            }
        }
        // 检查状态是否正常
        if (mallCustomer.getState() == 0) {
            throw new BizException(ErrorCodeEnum.USER_DENY);
        }
        return new LoginUser<>(username, mallCustomer.getPassword(),
                AuthorityUtils.createAuthorityList("ROLE_USER"), mallCustomer);
    }
}
